package com.javabasic.algorithm.leetcode;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see [917. Reverse Only Letters](https://leetcode-cn.com/problems/reverse-only-letters/)
 * @since Created by work on 2022/2/23 11:39 下午
 */
public class ReverseOnlyLetters {

    public static void main(String[] args) {
//        String str = "ab-cd";
        String str = "7_28]";
        reverseOnlyLetters(str);
    }

    /**
     * 双指针解法
     * @param s
     * @return
     */
    public static String reverseOnlyLetters(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        int len = s.length();
        int left = 0, right = len - 1;
        char[] resultChars = new char[len];
        while (left <= right) {
            while (left <= right && left < len && !(s.charAt(left) >= 'a' && s.charAt(left) <= 'z') && !(s.charAt(left) >= 'A' && s.charAt(left) <= 'Z')) {
                resultChars[left] = s.charAt(left);
                left++;
            }
            while (left <= right && right >= 0 && !(s.charAt(right) >= 'a' && s.charAt(right) <= 'z') && !(s.charAt(right) >= 'A' && s.charAt(right) <= 'Z')) {
                resultChars[right] = s.charAt(right);
                right--;
            }
            if (left <= right) {
                char temp = s.charAt(left);
                resultChars[left] = s.charAt(right);
                resultChars[right] = temp;
                left++;
                right--;
            }
        }
        return String.valueOf(resultChars);
    }
}
